package com.kkb.kkbportal.service.impl;

import com.github.pagehelper.PageHelper;
import com.kkb.kkbcommon.api.CommonPage;
import com.kkb.kkbcommon.service.RedisService;
import com.kkb.kkbportal.domain.dto.UserDto;
import com.kkb.kkbportal.domain.vo.DetailAvgStarVo;
import com.kkb.kkbportal.domain.vo.DetailBaseInfoVo;
import com.kkb.kkbportal.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class FameServiceImpl implements FameService {

    /**
     * redis数据结构的key
     */
    private static final String STUDENT_KEY = "student";
    private static final String TUTOR_KEY = "tutor";
    @Autowired
    private UserService userService;
    @Autowired
    private ScoreService scoreService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ProjectRegisterService projectRegisterService;


    /**
     * 根据导师/学员id，查询基本信息
     *
     * @param id 导师/学员id
     * @return 基本信息：基本个人资料、综合得分、完成项目数
     */
    @Override
    public DetailBaseInfoVo selectBaseInfoById(Long id) {

        // 1. userService查询基本个人资料
        UserDto userDto = userService.selectUserInfoById(id);

        // 2. scoreService查询综合得分
        List<DetailAvgStarVo> avgStarList = scoreService.avgStarListBySlaveId(id);

        // 3. projectService查询完成的项目数
        Integer completedProjectCount = projectRegisterService.completedProjects(id);


        // 4. 根据获取到的数据，构造DetailsBaseInfoVo对象，并返回前端
        DetailBaseInfoVo detailsBaseInfoVo = new DetailBaseInfoVo(userDto, avgStarList, completedProjectCount);

        return detailsBaseInfoVo;
    }

    @Override
    public List<DetailBaseInfoVo> listPage(Long roleId, Integer pageNum, Integer pageSize) {
        // TODO 暂时设置排行榜范围是前50名
        Set<Object> set = roleService.selectByRoleName("导师").getId().equals(roleId) ?
                redisService.zReverseRange(TUTOR_KEY, 0, 50) : redisService.zReverseRange(STUDENT_KEY, 0, 50);
        PageHelper.startPage(pageNum, pageSize);
        List<DetailBaseInfoVo> list = new ArrayList<>();
        // ans 当前排名
        int ans = 1;
        for (Object id : set) {
            Long userId = (Long) id;
            UserDto user = userService.selectUserInfoById(userId);
            List<DetailAvgStarVo> star = new ArrayList<>();
            DetailBaseInfoVo vo = new DetailBaseInfoVo(user, ans,
                    scoreService.avgStarListBySlaveId(userId), projectRegisterService.completedProjects(userId));
            ans++;
            list.add((vo));
        }
        return list;
    }
}
